package dao

import (
	"gorm.io/gorm"
	"srv/config"
	pb "srv/proto"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(30);comment:'用户名'"`
	Password string `gorm:"type:char(32);comment:'密码'"`
}

type Video struct {
	gorm.Model
	UserId           int    `gorm:"type:int(10);comment:'用户id'"`
	VideoUrl         string `gorm:"type:varchar(255);comment:'视频地址'"`
	VideoCover       string `gorm:"type:varchar(255);default:'';comment:'视频封面'"`
	VideoStatus      int8   `gorm:"type:tinyint(1);default:0;comment:'视频发布状态:0-发布,1-草稿'"`
	VideoAdoptStatus int8   `gorm:"type:tinyint(1);default:0;comment:'视频通过状态:0-未通过,1-已通过'"`
	Type             int8   `gorm:"type:tinyint(1);default:0;comment:'视频推荐类型:0-生活,1-游戏,2-美食'"`
}

// 用户登录注册一体化
func (u *User) UserRegister() (uint, string) {
	var user User
	config.DB.Where("username=?", u.Username).First(&user)
	//如果等于0进行注册
	if user.ID == 0 {
		err := config.DB.Create(&u).Error
		if err != nil {
			return 0, "用户注册失败"
		}
		return u.ID, ""
	} else {
		if user.Password != u.Password {
			return 0, "用户密码错误，登录失败"
		}
		return user.ID, ""
	}
}

// 视频发布
func (v *Video) VideoCreate() (uint, string) {
	var user User
	config.DB.Where("id=?", v.UserId).First(&user)
	if user.ID == 0 {
		return 0, "该用户不存在"
	}
	err := config.DB.Create(&v).Error
	if err != nil {
		return 0, "视频发布失败"
	}
	return v.ID, ""
}

// 视频列表
func (v *Video) VideoList(page, size int) ([]*pb.List, string) {
	var lists []*pb.List
	var vv []Video
	err := config.DB.Scopes(Paginate(page, size)).Find(&vv).Error
	if err != nil {
		return nil, "列表获取失败"
	}
	for _, video := range vv {
		list := pb.List{
			VideoUrl:   video.VideoUrl,
			VideoCover: video.VideoCover,
		}
		lists = append(lists, &list)
	}
	return lists, ""
}

// 分页
func Paginate(page, size int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case size > 100:
			size = 100
		case size <= 0:
			size = 10
		}
		offset := (page - 1) * size
		return db.Offset(offset).Limit(size)
	}
}

// 用户主页
func (v *Video) UserShow(id int) ([]*pb.List, string) {
	var lists []*pb.List
	//等于1为自己的账号
	if id == 1 {
		var vv []Video
		err := config.DB.Where("user_id=?", id).Find(&vv).Error
		if err != nil {
			return nil, `主页视频获取失败`
		}
		for _, video := range vv {
			list := pb.List{
				VideoUrl:   video.VideoUrl,
				VideoCover: video.VideoCover,
			}
			lists = append(lists, &list)
		}
		return lists, ""
	} else {
		var vv []Video
		err := config.DB.Where("user_id=?", id).Where("video_status=? and video_adopt_status=?", 0, 1).Find(&vv).Error
		if err != nil {
			return nil, "主页视频获取失败"
		}
		for _, video := range vv {
			list := pb.List{
				VideoUrl:   video.VideoUrl,
				VideoCover: video.VideoCover,
			}
			lists = append(lists, &list)
		}
		return lists, ""
	}
}
